import type {
  VxeGridProps,
  VxeGridPropTypes,
  VxeTableGridOptions,
} from '@vben/plugins/vxe-table';

import type { OnActionClickFn, OnActionClickParams } from '#/adapter/vxe-table';
import type { DefDictModel } from '#/api/devOperation/system/model/defDictModel';

import { ref } from 'vue';

import { i18n } from '@vben/locales';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { isEmptyOrUnDef } from '@vben/utils';

import { findAll } from '#/api';
import { DefDictApi } from '#/api/devOperation/system/defDict';
import { DictEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import { useDictStore } from '#/store';

/**
 * 生成表格列配置
 * @param onActionClick 操作按钮点击事件处理函数
 */
export function useColumns(
  onActionClick: OnActionClickFn<DefDictModel.DefDictResultVO>,
): VxeTableGridOptions<DefDictModel.DefDictResultVO>['columns'] {
  return [
    { type: 'checkbox', width: 50 },
    { title: $t('common.title.seq'), type: 'seq', width: 50 },
    { type: 'expand', width: 50, slots: { content: 'expandedRowRender' } },
    {
      field: 'key',
      title: $t('devOperation.system.defDict.key'),
    },
    {
      field: 'name',
      title: $t('devOperation.system.defDict.name'),
    },
    {
      field: 'exist',
      title: '是否存在',
      cellRender: {
        name: 'CellDict',
        attrs: {
          type: DictEnum.BooleanEnum,
          tag: true,
        },
      },
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'name',
          nameTitle: $t('devOperation.system.defDict.table.title'),
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'import',
            text: $t('common.title.import'),
          },
        ],
      },
      field: 'operation',
      fixed: 'right',
      headerAlign: 'center',
      showOverflow: false,
      title: $t('ui.actionTitle.operation'),
      width: 100,
    },
  ];
}

/**
 * 异步请求
 */
const gridAjax: VxeGridPropTypes.ProxyConfig<DefDictModel.DefDictResultVO> = {
  ajax: {
    query: async () => {
      return await findAll();
    },
  },
};

export function useIndex() {
  const { createMessage, createConfirm } = useMessage();

  const dictStore = useDictStore();
  const groupList = dictStore.getDictItemOptionList(
    DictEnum.DICT_GROUP,
    (i18n.global.locale as any).value,
  );
  const whetherList = dictStore.getDictItemList(DictEnum.BooleanEnum);
  const groupRef = ref<{ label: string; value: string }>();

  function onActionClick({
    code,
    row,
  }: OnActionClickParams<DefDictModel.DefDictResultVO>) {
    switch (code) {
      default: {
        handleImport(row);
        break;
      }
    }
  }
  const gridProps: VxeGridProps<DefDictModel.DefDictResultVO> = {
    gridOptions: {
      columns: useColumns(onActionClick),
      height: 'auto',
      keepSource: true,
      rowConfig: {
        isCurrent: true,
        isHover: true,
        keyField: 'uniqKey',
      },
      pagerConfig: { enabled: false },
      proxyConfig: {
        ...gridAjax,
      },
      toolbarConfig: {
        custom: true,
        export: false,
        refresh: true,
        search: true,
        zoom: true,
      },
    },
  };
  /**
   * 初始化表格组件
   */
  const [Grid, gridApi] =
    useVbenVxeGrid<DefDictModel.DefDictResultVO>(gridProps);

  async function handleImport(row: DefDictModel.DefDictResultVO) {
    batchImport([row]);
  }

  async function batchImport(selectRecords: DefDictModel.DefDictResultVO[]) {
    if (isEmptyOrUnDef(groupRef.value?.value)) {
      createMessage.warning(
        $t('devOperation.system.defDict.tips.selectDictGroup'),
      );
      return;
    }
    const list = selectRecords.map((item) => ({
      name: item.name,
      key: item.key,
      dataType: item.dataType,
      dictGroup: groupRef.value?.value,
      itemList: item.itemList,
    }));

    createConfirm({
      iconType: 'warning',
      title: $t('devOperation.system.defDict.tips.syncEnumDict'),
      content: $t('devOperation.system.defDict.tips.syncEnumDictConfirm', {
        count: selectRecords.length,
        label: groupRef.value?.label,
      }),
      onOk: async () => {
        await DefDictApi.importDictByEnum(list);
        createMessage.success($t('common.tips.importSuccess'));
        gridApi.reload();
      },
    });
  }

  async function handleBatchImport() {
    const selectRecords = gridApi.grid.getCheckboxRecords();
    if (selectRecords.length <= 0) {
      createMessage.warning($t('common.tips.pleaseSelectTheData'));
      return;
    }

    batchImport(selectRecords);
  }

  return { Grid, handleBatchImport, groupRef, groupList, whetherList };
}
